from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional, List
from pathlib import Path

from .config import settings
from .services.gemini_manager import GeminiManager
from .services.theme_generator import ThemeGenerator
from .services.content_generator import ContentGenerator
from .services.image_generator import ImageGenerator

app = FastAPI(title="AI Wallpaper Generator")

# 初始化服务
gemini_manager = GeminiManager()
theme_generator = ThemeGenerator(gemini_manager)
content_generator = ContentGenerator(gemini_manager)
image_generator = ImageGenerator(gemini_manager)


class WallpaperRequest(BaseModel):
    theme_type: Optional[str] = None
    prompt_count: Optional[int] = 10


class WallpaperResponse(BaseModel):
    theme: dict
    title: str
    description: str
    images: List[dict]


@app.post("/generate-wallpaper", response_model=WallpaperResponse)
async def generate_wallpaper(request: WallpaperRequest):
    try:
        # 1. 生成主题
        theme = await theme_generator.generate_theme(request.theme_type)
        
        # 2. 生成标题和描述
        title = await content_generator.generate_title(theme)
        description = await content_generator.generate_seo_description(theme, title)
        
        # 3. 生成图片提示词
        prompts = await content_generator.generate_prompts(theme, request.prompt_count)
        
        # 4. 生成图片
        image_results = await image_generator.generate_batch(prompts)
        
        # 5. 构建响应
        images = [
            {
                "prompt": prompt,
                "path": str(path.relative_to(settings.IMAGE_OUTPUT_PATH))
            }
            for prompt, path in image_results
        ]
        
        return {
            "theme": theme,
            "title": title,
            "description": description,
            "images": images
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.on_event("startup")
async def startup_event():
    """启动时初始化必要的目录"""
    settings.initialize()
